var table;
var insTb;
var enable;
var renderTable;
var BSTable = function(options, $this) {
    var treeTable;
    var searchForm = options.searchForm ? options.searchForm: $("#searchForm");
    enable = options.treeEnable;
    options = $.extend({
            btnSearch: $("#btnSearch"),
            page: {layout: ['prev', 'page', 'next', 'skip','count'] },
            id:"btGrid",
            elem: '#btGrid',//指定表格元素
            method:'POST',
            loading: false, //请求数据时，是否显示loading
            even: true,
            text: {
                none: '暂无相关数据'
            },
            limit: 15,
            where: getParams(),
            request:{
                pageName: 'pageNo' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            url: searchForm.attr("action"),
            cols: [options.columnModel],
            parseData: function(res){
                if(options.page){
                    return {
                        "code": 0,
                        "msg": "",
                        "count": res.count, //解析数据长度
                        "data": res.list == undefined ? [] : res.list //解析数据列表
                    };
                }else{
                    return {
                        "code": 0,
                        "msg": "",
                        "count": 0, //解析数据长度
                        "data": res == undefined ? [] : res //解析数据列表
                    };
                }
            },
            done: function(res, curr, count) {
                if (typeof options.ajaxSuccess == "function") {
                    options.ajaxSuccess(res)
                }
                if (res && res.message) {
                    js.showMessage(res.message)
                }
                if (typeof btnEventBind == "function") {
                    btnEventBind($(".btnList"));
                }
                $(".btn").attr("disabled", false);
                resizeDataGrid();
            },
        },
        options);
    if (typeof btnEventBind == "function") {
        btnEventBind($(".btnTool"));
        options.btnSearch.click(function() {
            var btnSearch = $(this);
            if (searchForm.hasClass("d-none")) {
                searchForm.removeClass("d-none");
                btnSearch.html(btnSearch.html().replace("查询", "隐藏"))
            } else {
                searchForm.addClass("d-none");
                btnSearch.html(btnSearch.html().replace("隐藏", "查询"))
            }
            resizeDataGrid()
        })
    }
    //渲染表格
    layui.config({
        base: ctxStatic+'/layui/'
    }).extend({
        treeTable: 'treeTable/treeTable'
    }).use(['table', 'treeTable'], function() {
        table = layui.table;
        treeTable = layui.treeTable;
        if(options.treeEnable){//树结构初始化
            renderTable = function(){
                js.ajaxRequest(searchForm.attr("action"),getParams(),function (data, status, xhr) {
                    for (var i = 0;i<data.length;i++){
                        data[i].haveChild = isHaveChild(data,data[i].id);
                    }
                    options.data = data;
                    options.cols = options.columnModel;
                    options.tree = {
                        iconIndex: 0,
                        isPidData: true,
                        pidName: 'id',
                        pidName: 'parentId',
                        arrowType: 'arrow2',
                        getIcon: function (d) {//自定义图标
                            if(options.isFile){
                                if (d.haveChild) {
                                    return '<i class="ew-tree-icon ew-tree-icon-folder"></i>';
                                } else {
                                    return '<i class="ew-tree-icon ew-tree-icon-file"></i>';
                                }
                            }
                            else {
                                return '';
                            }
                        }
                    };
                    insTb = treeTable.render(options);
                    btnEventBind($(".btnList"));
                });
            }
            renderTable();
            $('#btnExpandTreeNode').click(function () {
                insTb.expandAll();
            });

            $('#btnCollapseTreeNode').click(function () {
                insTb.foldAll();
            });

            $('#btnRefreshTree').click(function () {
                renderTable();
            });
        }else{
            table.render(options);//普通表格初始化
        }

    });
    searchForm.submit(function() {
        refresh();
        return false
    });
    $(window).resize(function() {
        resizeDataGrid()
    });
    function resizeDataGrid() {
        var setGridHeight = function() {
            var lay_table = $("div[class='layui-table-body layui-table-main'] table");
            var gridHeight = lay_table.height();
            var gridParent = lay_table.parent();
            if (gridParent.length != 0) {
                gridHeight = gridParent.height()-10;
            }
            js.print("设置前：window:" + $(window).height() + " body:" + $("body").height() + " table:" + $("div[class='layui-table-body layui-table-main'] table").height() + " table-parent:" + gridHeight);
            gridHeight = ($(window).height() - $("body").height() + gridHeight);
            if (gridHeight < 150) {
                gridHeight = 150
            }
            gridParent.height(gridHeight);
            table.resize('btGrid');
            js.print("设置后：window:" + $(window).height() + " body:" + $("body").height() + " table:" + $("div[class='layui-table-body layui-table-main'] table").height() + " table-parent:" + gridHeight)
        };
        setGridHeight()
    }
};
$.fn.BTGrid = function(option) {
    var $set = this.each(function() {
        var $this = $(this);
        var data = $this.data("btGrid");
        var options = typeof option === "object" && option;
        if (!data) {
            data = new BSTable(options, $this);
            window[$this.attr("id")] = data;
            $this.data("btGrid", data)
        }
    });
    return $set
};
function refresh() {
    if(enable){
        renderTable();
    }else {
        table.reload('btGrid',{
            where: getParams(),
            // page: { pageNo: pageNum}
        })
    }
}
function btnEventBind(elements) {
    elements.each(function() {
        var clickBinded = $(this).attr("data-click-binded");
        if (clickBinded == undefined) {
            $(this).attr("data-click-binded", true);
            $(this).click(function() {
                var se = $(this);
                var url = se.attr("href");
                var title = se.data("title");
                if (title == undefined) {
                    title = se.attr("title")
                }
                var confirm = se.data("confirm");
                var prompt = se.data("prompt");
                if (confirm != undefined) {
                    js.confirm(confirm, url,
                        function(data) {
                            js.showMessage(data.message);
                            if (data.result == "true") {
                                var confirmSuccess = se.data("confirmSuccess");
                                if (confirmSuccess != undefined) {
                                    try {
                                        eval(confirmSuccess)
                                    } catch(e) {
                                        js.print("confirmSuccess error: " + e)
                                    }
                                }else{
                                    refresh();
                                }
                            }
                        },
                        "json")
                } else {
                    if (prompt != undefined) {
                        js.prompt(prompt, url,
                            function(data) {
                                js.showMessage(data.message);
                                if (data.result == "true") {
                                    refresh()
                                }
                            },
                            "json")
                    } else {
                        var type = se.data("type");
                        if (type != undefined && type == "layer") {
                            js.layer.open({
                                type: 2,
                                title: title,
                                shade: false,
                                shadeClose: false,
                                maxmin: true,
                                area: ["100%", "100%"],
                                content: url,
                                end: function() {
                                    refresh()
                                }
                            })
                        } else {
                            if (type != undefined && type == "diagram") {
                                js.layer.open({
                                    type: 2,
                                    title: title,
                                    shade: 0.3,
                                    shadeClose: true,
                                    maxmin: true,
                                    area: ["80%", "80%"],
                                    content: url,
                                    end: function() {}
                                })
                            } else {
                                if (type != undefined && type == "form") {
                                    var formTitle = se.data("formtitle");
                                    var formUrl = se.data("formurl");
                                    var wh = se.data("wh");
                                    js.form(formTitle, url, formUrl,
                                        function(data) {
                                            if (data.result == "true") {
                                                js.showMessage(data.message);
                                                refresh()
                                            } else {
                                                js.showErrorMessage(data.message)
                                            }
                                        },
                                        "json", wh)
                                } else {
                                    var win;
                                    if (window.tabpanel) {
                                        win = window
                                    }
                                    if (parent.tabpanel) {
                                        win = window.parent
                                    }
                                    if (parent.parent.tabpanel) {
                                        win = window.parent.parent
                                    }
                                    if (top.tabpanel) {
                                        win = top
                                    }
                                    win.addTabPage($(this), title, url, true, true)
                                }
                            }
                        }
                    }
                }
                return false
            })
        }
    });
    return self
}
function getParams(){
    var map = {};
    var param = $("#searchForm").serialize();
    var params = param.split("&");
    for (var i = 0; i < params.length; i++) {
        var p = params[i];
        var nv = p.split("=");
        map[nv[0]] = nv[1]
    }
    console.log(map);
    return map;
}
function isHaveChild(data,pid){
    var flag = false;
    for(var i =0;i<data.length;i++){
        if(data[i].parentId == pid){
            flag = true;
            break;
        }
    }
    return flag;
}